package com.hk.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    @Autowired
    private MyRealm myRealm;

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager() {
        //1、创建默认的管理器
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //2、创建加密对象
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        matcher.setHashIterations(3);
        //3、将加密对象存储到myRealm中
        myRealm.setCredentialsMatcher(matcher);

        //4、将myRealm存储到默认的管理器中
        defaultWebSecurityManager.setRealm(myRealm);

        ThreadContext.bind(defaultWebSecurityManager);
        return defaultWebSecurityManager;
    }


    @Bean
    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        //设置可以直接访问的路径
        definition.addPathDefinition("/myController/login", "anon");
        definition.addPathDefinition("/myController/userLogin", "anon");
        //设置登录要拦截范围
        definition.addPathDefinition("/**", "authc");

        return definition;
    }
}
